import React, { Component } from "react";

class ImageTrigger extends Component {
  state = {
    url: this.props.defaultUrl,
    isDefaultUrl: true,
  };

  handleHover = (isMouseEnter) => {
    const { trigger, defaultUrl, triggerUrl } = this.props;
    if (trigger === "hover") {
      this.setState({ url: isMouseEnter ? triggerUrl : defaultUrl });
    }
  };

  handleClick = () => {
    const { trigger, defaultUrl, triggerUrl, onClick } = this.props;
    const { isDefaultUrl } = this.state;
    onClick && onClick();
    if (trigger === "click") {
      this.setState({
        isDefaultUrl: !isDefaultUrl,
        url: isDefaultUrl ? triggerUrl : defaultUrl,
      });
    }
  };

  render() {
    const { className, style } = this.props;
    const { url } = this.state;
    return (
      <img
        src={url}
        alt=""
        className={className}
        style={Object.assign({ cursor: "pointer" }, style)}
        onMouseEnter={() => this.handleHover(true)}
        onMouseLeave={() => this.handleHover(false)}
        onClick={this.handleClick}
      />
    );
  }
}

ImageTrigger.propTypes = {
  trigger: React.PropTypes.string, // 触发鼠标事件 hover click
  defaultUrl: React.PropTypes.string.isRequired, // 默认url
  triggerUrl: React.PropTypes.string.isRequired, // 触发后的url
  className: React.PropTypes.string,
  style: React.PropTypes.object,
  onClick: React.PropTypes.func,
};

ImageTrigger.defaultProps = {
  trigger: "hover",
  style: {},
  onClick: () => {},
};

export default ImageTrigger;
